package com.shop.zkmall.app.controller.a;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.shop.zkmall.app.controller.a.live.LiveService;
import com.shop.zkmall.app.domain.CereBuyerLiveRoom;
import com.shop.zkmall.app.mapper.CereBuyerLiveRoomMapper;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("liveCallBack")
@RequiredArgsConstructor
@Tag(name = "直播模块", description = "直播模块")
public class LiveCallbackController {


    @Autowired
    private CereBuyerLiveRoomMapper cereBuyerLiveRoomMapper;


    /**
     * 直播开始回调
     *
     * @param data
     * @return
     */
    @PostMapping("/callback/streamOnline")
    public String streamOnline(@RequestBody Map<String, Object> data) {

        String streamId = (String) data.get("stream_id");

        // 查询直播间
        QueryWrapper<CereBuyerLiveRoom> wrapper = new QueryWrapper<>();
        wrapper.eq("stream_name", streamId);
        CereBuyerLiveRoom room = cereBuyerLiveRoomMapper.selectOne(wrapper);

        if (room != null) {
            room.setStatus(1);  // 正在直播
            room.setStartTime(LocalDateTime.now());
            cereBuyerLiveRoomMapper.updateById(room);
        }

        return "OK";
    }


    /**
     * 直播暂停回调
     *
     * @param data
     * @return
     */
    @PostMapping("/callback/streamDisconnect")
    public String streamDisconnect(@RequestBody Map<String, Object> data) {

        String streamId = (String) data.get("stream_id");

        CereBuyerLiveRoom room = cereBuyerLiveRoomMapper.selectOne(
                new QueryWrapper<CereBuyerLiveRoom>().eq("stream_name", streamId)
        );

        if (room != null) {
            room.setStatus(3); // 暂停中
            cereBuyerLiveRoomMapper.updateById(room);
        }
        return "OK";
    }



    /**
     * 直播结束回调
     *
     * @param data
     * @return
     */
    @PostMapping("/callback/streamOffline")
    public String streamOffline(@RequestBody Map<String, Object> data) {

        String streamId = (String) data.get("stream_id");

        QueryWrapper<CereBuyerLiveRoom> wrapper = new QueryWrapper<>();
        wrapper.eq("stream_name", streamId);
        CereBuyerLiveRoom room = cereBuyerLiveRoomMapper.selectOne(wrapper);

        if (room != null) {
            room.setStatus(2);  // 已结束
            room.setEndTime(LocalDateTime.now());
            cereBuyerLiveRoomMapper.updateById(room);
        }

        return "OK";
    }



}
